import sys
import time
import socket
import select
import threading
import cPickle as cpickle

#HOST            = sys.arg[0]
#PORT            = sys.arg[1]
MAX_THREADS     = 2 #sys.arg[2]
MAX_LENGTH      = 2**15

class RequestHandler(threading.Thread):
    global MAX_LENGTH
    def __init__(self, (client, address)):
        threading.Thread.__init__(self)
        self.running      = False
        self.client       = client
        self.setDaemon(0)
        self.start()
    def run(self):
        running = True
        while running:
            data = self.client.recv(MAX_LENGTH)
            end = data.find('(')
            func = eval('self.do_' + data[:end])
            param = cpickle.loads(data[end+1:])
            if len(param) == 0:
                func()
            if len(param) == 1:
                func(param[0])
            if len(param) == 2:
                func(param[0], param[1])
    def do_register(self, options):
        pass
    def do_notify(self, options):
        pass
    def do_invite(self, options):
        pass
    def do_ok(self, options):
        pass
    def do_cancel(self):
        pass
    def do_trying(self):
        pass
    def do_ringing(self):
        pass
    def do_ack(self):
        pass
    def do_bye(self):
        pass

class Uac(threading.Thread):
    global MAX_LENGTH
    def __init__(self, (host, port)):
        threading.Thread.__init__(self)
        self.address = (host, port)
        

class Uas(threading.Thread):
    global MAX_LENGTH
    def __init__(self, (host, port)):
        threading.Thread.__init__(self)
        self.handlers        = []
        self.handlerslock    = threading.Lock()
        self.address         = (host, port)
        self.socket          = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.inqueue         = [self.socket, sys.stdin]
        self.socket.bind(self.address)
        self.socket.listen(1)
        self.start()
    def run(self):
        running = True
        while running:
            inqueue, outqueue, errqueue = select.select(self.inqueue, [], [])
            for request in inqueue:
                if request == self.socket:
                    handler = RequestHandler(request.accept())
                    self.handlers.append(self.handlers)
                elif request == sys.stdin:
                    request.readline()
                    running = False
        self.socket.close()
        for handler in self.handlers:
            handler.join()


if __name__ == '__main__':
    s = Uas(('localhost', 50055))
    s.join()
